import React, { createElement, FC, useEffect, useRef, useState } from 'react';
import { Col, Row } from 'antd';
import { FormItem, withForm } from 'react-antd-formutil';
import Sortable from 'sortablejs';
import Draggable from '../../components/Draggable';
import { eventBus } from '../../utils';
import { components, PickerItemData } from '../Picker/config';
import './style.css';
import Block from './Block';

function Canvas() {
    const [list, setList] = useState<PickerItemData[]>([]);
    const { current: listRef } = useRef({
        list,
        current: undefined as PickerItemData | undefined,
        find: (key: string) => listRef.list.find(item => item.key === key),
        set: (data: PickerItemData[]) => (listRef.list = data),
        onChoose(event) {
            listRef.current = listRef.find(event.item.dataset.key);

            eventBus.emit('edit:item', listRef.current);
        }
    });
    const sortableRef = useRef<Sortable>();
    const wrapRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        listRef.set(list);
        eventBus.emit('build:json', list);
    }, [list]);

    useEffect(() => {
        if (wrapRef.current) {
            sortableRef.current = new Sortable(wrapRef.current, {
                group: 'shared',
                animation: 150,
                onAdd(event) {
                    if (event.from.classList.contains('panel-picker')) {
                        event.item.remove();
                    }
                },
                onChoose: listRef.onChoose
            });
        }

        eventBus.on('push:canvas', data => {
            setList(list => list.concat(data));
        });

        eventBus.on('update:item', (data, key) => {
            if (key && data && listRef.current) {
                Object.assign(listRef.current, data);

                setList(list => [...list]);
            }
        });
    }, []);

    return (
        <div className="panel-canvas" ref={wrapRef}>
            {list.map(item => (
                <Block data={item} key={item.key} data-key={item.key} onChoose={listRef.onChoose} />
            ))}
        </div>
    );
}

export default withForm(Canvas);
